package com.gifts.ui.page.selectafriend;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.InputStream;
import java.util.List;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JRootPane;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.eclipse.swt.SWT;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;

import com.gifts.service.FacebookService;
import com.gifts.service.GoogleShoppingService;
import com.gifts.service.client.GoogleShoppingClient;
import com.gifts.service.entity.FacebookUser;
import com.gifts.service.entity.GoogleProduct;
import com.gifts.service.entity.GoogleShoppingObj;
import com.gifts.ui.page.common.JMainPanel;
import com.gifts.ui.page.common.JThumbnail;
import com.gifts.ui.page.common.JThumbnailPanel;
import com.gifts.ui.page.common.JThumbnailPanel;
import com.gifts.ui.page.common.Page;
import com.gifts.ui.page.common.PageFactory;
import com.gifts.ui.page.selectaProduct.JFilterPricePanel;
import com.gifts.ui.page.selectaProduct.JListInterestsPanel;
import com.gifts.ui.page.selectaProduct.JListProductsPanel;
import com.gifts.ui.page.selectaProduct.JSelectAProductPanel;
import com.gifts.ui.page.selectaProduct.SelectAProductPage;
import com.gifts.utils.BareBonesBrowserLaunch;
import com.izforge.izpack.UpdateCheck;
/**
 * Main Class for SelectAfriendPage
 * @author dmaung,kevin
 *
 */
public class SelectAFriendsPage extends Page {

	/**
	 * A service for facebook
	 */
	FacebookService facebookService = FacebookService.getInstance();
	GoogleShoppingService googleShoppingService = GoogleShoppingService
			.getInstance();

	private JMainPanel mainPanel;

	/**
	 * select A friendsPanel;
	 */
	private JSelectAFriendsPanel selectAFriendsPanel;

	private java.awt.Container contentPane;

	/**
	 * listSuggestionPanel
	 */
	private JSelectAProductPanel selectAProductPanel;

	public SelectAFriendsPage(Composite parent, int style) {

		super(parent, SWT.EMBEDDED | SWT.NO_BACKGROUND);
		init();

	}

	private boolean init = false;

	public void init() {
		/* Create and setting up frame */
		Frame frame = SWT_AWT.new_Frame(this);

		setSize(new Point(800, 680));
		Panel panel = new Panel(new BorderLayout()) {
			public void update(java.awt.Graphics g) {
				/* Do not erase the background */
				paint(g);
			}
		};

		frame.add(panel);
		JRootPane root = new JRootPane();

		panel.add(root);
		contentPane = root.getContentPane();
		BorderLayout borderLayout = new BorderLayout();

		contentPane.setLayout(borderLayout);

		selectAFriendsPanel = new JSelectAFriendsPanel();
		selectAProductPanel = new JSelectAProductPanel();

		mainPanel = new JMainPanel();
		showSelectAFriendPanel();

		mainPanel.getHomeButton().addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				showSelectAFriendPanel();

			}

		});

		final JListInterestsPanel jListInterestsPanel = selectAProductPanel
				.getJListInterestsPanel();

		jListInterestsPanel.getInterestComboBox().addItemListener(
				new ItemListener() {

					@Override
					public void itemStateChanged(ItemEvent e) {
						int state = e.getStateChange();
						if (state == ItemEvent.SELECTED) {
							// if(init) {

							String item = (String) jListInterestsPanel
									.getInterestComboBox().getSelectedItem();
							JFilterPricePanel filterPricePanel = selectAProductPanel
									.getJListProductPanel().getJSearchPanel();

							JTextField minJTextField = filterPricePanel
									.getMinJTextField();
							JTextField maxJTextField = filterPricePanel
									.getMaxJTextField();
							minJTextField.setText("");
							maxJTextField.setText("");

							loadListProductsPanel(item, null, null);
							// } else {
							// init= true;
							// }

						}

					}
				});

		JButton submitButton = selectAProductPanel.getJListInterestsPanel()
				.getSubmitButton();
		submitButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				String keyword = selectAProductPanel.getJListInterestsPanel()
						.getInterestTextField().getText();

				JFilterPricePanel filterPricePanel = selectAProductPanel
						.getJListProductPanel().getJSearchPanel();

				JTextField minJTextField = filterPricePanel.getMinJTextField();
				JTextField maxJTextField = filterPricePanel.getMaxJTextField();
				minJTextField.setText("");
				maxJTextField.setText("");
				loadListProductsPanel(keyword, null, null);

			}

		});

		selectAProductPanel.getJListProductPanel().getJSearchPanel()
				.getSubmitButton().addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent arg0) {
						JFilterPricePanel filterPricePanel = selectAProductPanel
								.getJListProductPanel().getJSearchPanel();
						JTextField minJTextField = filterPricePanel
								.getMinJTextField();
						JTextField maxJTextField = filterPricePanel
								.getMaxJTextField();
						JLabel errorMessageLabel = filterPricePanel
								.getErrorMessageLabel();
						String minprice = minJTextField.getText();
						String maxPrice = maxJTextField.getText();
						try {
							if (minprice.trim().length() == 0) {
								errorMessageLabel
										.setText("You must enter Min Price");
								return;
							}
							if (maxPrice.trim().length() == 0) {
								errorMessageLabel
										.setText("You must enter Max Price");
								return;
							}
							
							
							Double minPriceInt = Double.parseDouble(minprice);
							Double maxPriceInt = Double.parseDouble(maxPrice);
							if(minPriceInt >= maxPriceInt) {
								errorMessageLabel.setText("Min Price  must be smaller than Max price");
								return;
							}
							String keyword = selectAProductPanel
									.getJListInterestsPanel()
									.getInterestTextField().getText();
							if (keyword.trim().length() == 0) {
								keyword = (String) selectAProductPanel
										.getJListInterestsPanel()
										.getInterestComboBox()
										.getSelectedItem();
								if (keyword == null) {
									keyword = "gift card";
								}
							}
							errorMessageLabel.setText("");
							loadListProductsPanel(keyword, minPriceInt,
									maxPriceInt);

						} catch (NumberFormatException e) {
							errorMessageLabel.setText("Invalid Price");
						}

					}

				});
		JSearchFriendsPanel searchFriendsPanel = selectAFriendsPanel
				.getJSearchFriendsPanel();
		final JSearchPanel jSearchPanel = searchFriendsPanel.getJSearchPanel();
		jSearchPanel.getSubmitButton().addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				String name = jSearchPanel.getSearchBoxTextField().getText();

				List<FacebookUser> searchFriends = facebookService
						.searchFriends(name);
				loadSearchFriends(searchFriends);

			}

		});

		final JUpcomingBirthdayTopPanel jUpcomingBirthdayTopPanel = selectAFriendsPanel
				.getJUpcomingBirthdayPanel().getJUpcomingBirthdayTopPanel();
		jUpcomingBirthdayTopPanel.getDayCombox().addItemListener(
				new ItemListener() {

					@Override
					public void itemStateChanged(ItemEvent e) {
						int state = e.getStateChange();
						if (state == ItemEvent.SELECTED) {
							String day = (String) jUpcomingBirthdayTopPanel
									.getDayCombox().getSelectedItem();
							loadUpComingBirthdayPanel(Integer.parseInt(day));
						}

					}
				});

	}

	private void showSelectAFriendPanel() {
		contentPane.removeAll();
		contentPane.add(mainPanel, BorderLayout.NORTH);
		contentPane.add(selectAFriendsPanel, BorderLayout.CENTER);
		final JUpcomingBirthdayTopPanel jUpcomingBirthdayTopPanel = selectAFriendsPanel
				.getJUpcomingBirthdayPanel().getJUpcomingBirthdayTopPanel();
		String day = (String) jUpcomingBirthdayTopPanel.getDayCombox()
				.getSelectedItem();
		loadUpComingBirthdayPanel(Integer.parseInt(day));

		loadSearchAFrendsPanel();

		contentPane.repaint();
		contentPane.validate();
		mainPanel.getHomeButton().setVisible(false);

	}

	private void showSelectAProductPanel(final FacebookUser facebookUser) {

		contentPane.removeAll();
		contentPane.add(mainPanel, BorderLayout.NORTH);
		contentPane.add(selectAProductPanel, BorderLayout.CENTER);

		contentPane.repaint();
		List<String> interests = facebookService.filterInterests(facebookUser
				.getUserId());
		if (!interests.isEmpty()) {

			loadListSuggestionPanel(facebookUser, interests);
			// loadListProductsPanel(interests[0]);

		} else {
			loadListSuggestionPanel(facebookUser, interests);
			loadListProductsPanel("gift card", null, null);
		}

		mainPanel.getHomeButton().setVisible(true);
		// contentPane.repaint();

	}

	private void loadUpComingBirthdayPanel(int day) {
		try {

			List<FacebookUser> upcomingBirthdayFriends = facebookService
					.findUpcomingBirthdays(day);
			JUpcomingBirthdayPanel upcomingBirthdayPanel = selectAFriendsPanel
					.getJUpcomingBirthdayPanel();

			JThumbnailPanel thumnailPanel = upcomingBirthdayPanel
					.getJThumbnailPanel();
			cancel();
			thumnailPanel.removeAll();
			for (final FacebookUser upcomingBirthdayFriend : upcomingBirthdayFriends) {
				String thumbnailUrl = upcomingBirthdayFriend.getPicSmall();
				String name = upcomingBirthdayFriend.getName();
				String birthday = upcomingBirthdayFriend.getBirthdayShort() == null ? ""
						: upcomingBirthdayFriend.getBirthdayShort();

				thumnailPanel.addJThumnail(new MouseAdapter() {
					@Override
					public void mousePressed(MouseEvent e) {
						// super.mousePressed(e);
						showSelectAProductPanel(upcomingBirthdayFriend);

						System.out.println("interests:");
						System.out.println("MOUSE CLICKED");
					}

				}, thumbnailUrl, name, "     " + birthday + "     ");

			}
			thumnailPanel.loadIconsInBackground();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void loadSearchAFrendsPanel() {

		List<FacebookUser> allFriends = facebookService.searchFriends(null);
		loadSearchFriends(allFriends);
	}

	public void loadListSuggestionPanel(FacebookUser user,
			List<String> interests) {
		try {
			JListInterestsPanel listInterestPanel = selectAProductPanel
					.getJListInterestsPanel();
			JThumbnail thumbnail = listInterestPanel.getJThumbnail();
			JComboBox interestComboBox = listInterestPanel
					.getInterestComboBox();
			JLabel noResultLabel = listInterestPanel.getNoResultLabel();
			interestComboBox.removeAllItems();
			listInterestPanel.getInterestTextField().setText("");
			// String[] interests = user.getInterestsInArray();

			String thumbnailUrl = user.getPicSmall();
			String name = user.getName();

			thumbnail.setText(thumbnailUrl, name);
			if (!interests.isEmpty()) {

				for (String interest : interests) {
					interestComboBox.addItem(interest);
					interestComboBox.setVisible(true);
					listInterestPanel.getInterestLabel().setVisible(true);
					noResultLabel.setVisible(false);
				}
				interestComboBox.setSelectedItem(interests.get(0));

			} else {
				listInterestPanel.getInterestLabel().setVisible(false);
				noResultLabel.setVisible(true);
				interestComboBox.setVisible(false);
			}
			listInterestPanel.repaint();
			listInterestPanel.revalidate();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void loadListProductsPanel(String query, Double price1, Double price2) {
		try {

			GoogleShoppingObj googleShoppingObj = googleShoppingService.find(
					query, price1, price2);
			JListProductsPanel jListProductPanel = selectAProductPanel
					.getJListProductPanel();
			JThumbnailPanel thumnailPanel = jListProductPanel
					.getJThumbnailPanel();

			cancel();
			thumnailPanel.removeAll();
			System.out.println("Google Product: "
					+ googleShoppingObj.getProducts().length);
			GoogleProduct[] products = googleShoppingObj.getProducts();
			for (int i = 0; i < products.length; i++) {
				final GoogleProduct product = products[i];
				String thumbnailUrl = product.getImageLink();
				String name = product.getTitle();
				double price = product.getPrice();
				String seller = product.getSeller();
				if(seller.length() < 10) {
					seller = "    " + seller + "    ";
				}
				String priceStr = "      $" + price + "     ";
				thumnailPanel.addJThumbnail(new MouseAdapter() {
					@Override
					public void mousePressed(MouseEvent e) {

						super.mousePressed(e);

						String url = product.getProductLink();
						BareBonesBrowserLaunch.openURL(url);

					}
				}, thumbnailUrl, name, priceStr, seller);

			}
			thumnailPanel.loadIconsInBackground();
			thumnailPanel.repaint();
			thumnailPanel.revalidate();

		} catch (Exception e) {

		}

	}

	private void loadSearchFriends(List<FacebookUser> allFriends) {
		try {
			JSearchFriendsPanel searchFriendsPanel = selectAFriendsPanel
					.getJSearchFriendsPanel();
			JThumbnailPanel thumnailPanel = searchFriendsPanel
					.getJThumbnailPanel();
			cancel();
			thumnailPanel.removeAll();

			for (final FacebookUser friend : allFriends) {
				String thumbnailUrl = friend.getPic();
				String name = friend.getName();

				// JThumbnail jthumbnail = new JThumbnail(thumbnailUrl,name);
				thumnailPanel.addJThumbnail(new MouseAdapter() {
					@Override
					public void mousePressed(MouseEvent e) {
//						super.mousePressed(e);
						System.out.println("interests:");
						System.out.println("MOUSE CLICKED");

						showSelectAProductPanel(friend);

						
					}
				}, thumbnailUrl, name);

			}

			thumnailPanel.loadIconsInBackground();
			thumnailPanel.repaint();
			// thumnailPanel.revalidate();
		} catch (Exception e) {

		}

	}

	private void cancel() {

		JListProductsPanel jListProductPanel = selectAProductPanel
				.getJListProductPanel();
		JThumbnailPanel thumnailPanel = jListProductPanel.getJThumbnailPanel();
		thumnailPanel.cancel();

		JSearchFriendsPanel searchFriendsPanel = selectAFriendsPanel
				.getJSearchFriendsPanel();
		thumnailPanel = searchFriendsPanel.getJThumbnailPanel();

		thumnailPanel.cancel();

		// JUpcomingBirthdayPanel upcomingBirthdayPanel = selectAFriendsPanel
		// .getJUpcomingBirthdayPanel();
		//
		// thumnailPanel = upcomingBirthdayPanel
		// .getJThumbnailPanel();
		// thumnailPanel.cancel();

	}

}
